/* 01-thread.c

   Prints address space boundaries of all threads involved

   pthread.h should be first otherwise compile with -D_THREAD_SAFE 
*/
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>

#define NUM_THREADS     2

int x;

void *PrintHello(void *threadid) {
   long h=0;
   long tid;

   tid = (long)threadid;
   printf("\nIn thread #%ld", tid);
   printf("\nPid of PrintHello process is: %d", getpid());
   printf("\nAddresses:");
   printf("\n 1) Data: %p", &tid);
   printf("\n 2) Unitialized data: %p", &h);
   printf("\n 3) Code: %p\n", &PrintHello);
   pthread_exit(NULL);
}

int main (int argc, char *argv[]) {
   pthread_t threads[NUM_THREADS];
   int rc;
   long t = 0;

   printf("\nPid of the process is = %d", getpid());
   printf("\nMain addresses:");
   printf("\n 1) Data: %p", &rc);
   printf("\n 2) Unitialized data: %p", &t);
   printf("\n 3) Code: %p", &main);
   printf("\n 3) Stack: %p\n", &PrintHello);

   for (t=0; t < NUM_THREADS; t++) {
      printf("In main: creating thread %ld\n", t);
      rc = pthread_create(&threads[t], NULL, PrintHello, (void*)t);
      if (rc) {
         printf("ERROR; return code from pthread_create() is %d\n", rc);
         exit(-1);
      }
   }

   /* Last thing that main() should do */
   pthread_exit(NULL);
}
